package com.stxx.stiot2.gateway;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.stxx.framwork.constants.SceneActionType;
import com.stxx.framwork.exception.ServiceException;
import com.stxx.stiot2.domain.Gateway;
import com.stxx.stiot2.domain.ext.ReportData;
import com.stxx.stiot2.event.dto.P2tMsg;
import com.stxx.stiot2.event.dto.T2pMsg;
import com.stxx.stiot2.gateway.face.GatewayServer;
import org.dromara.mica.mqtt.server.solon.MqttServerTemplate;
import org.noear.solon.Solon;
import java.nio.charset.StandardCharsets;

public abstract class AbstractMqttServer implements GatewayServer {
    private MqttServerTemplate server;
    @Override
    public void init(Gateway gateway){
        server = Solon.context().getBean(MqttServerTemplate.class);
    }

    @Override
    public T2pMsg receive(String topic, String message){
        String [] strs = topic.split("/");
        String gatewayCode = strs[2];
        String terminalCode = strs[3];
        T2pMsg message2 = new T2pMsg();
        message2.setGatewayCode(gatewayCode);
        message2.setTerminalCode(terminalCode);
        message2.setData(JSON.parseObject(message, ReportData.class));
        return message2;
    }

    @Override
    public void send(String gatewayCode, String terminalCode, P2tMsg message){
        if(server==null){
            throw new ServiceException("网关未初始化或者已关闭");
        }
        if(StrUtil.equals(message.getType(), SceneActionType.READ.getValue())){
            StringBuilder sb = new StringBuilder();
            sb.append("/iot/").append(gatewayCode).append("/").append(terminalCode).append("/properties/get");
            server.publishAll(sb.toString(),message.getProperties().getBytes(StandardCharsets.UTF_8));
        }else{
            StringBuilder sb = new StringBuilder();
            sb.append("/iot/").append(gatewayCode).append("/").append(terminalCode).append("/properties/set");
            server.publishAll(sb.toString(),message.getProperties().getBytes(StandardCharsets.UTF_8));
        }
    }

    @Override
    public void close(){
        server = null;
    }
}
